var config = {
  aliyunServerURL: '', 
  AccessKeySecret: '',        
  accessid: '',       
	policyBase64:'',
	signature:'',
  timeout: 87600 ,
	expiration:'',
	SecurityToken:''
};
const base64 = require('./base64.js');//Base64,hmac,sha1,crypto相关算法
require('./hmac.js');
require('./sha1.js');
const Crypto = require('./crypto.js');

import Vue from 'vue';

/*
 *上传文件到阿里云oss
 *@param - filePath :图片的本地资源路径
 *@param - dir:表示要传到哪个目录下
 *@param - successc:成功回调
 *@param - failc:失败回调
 */ 

const uploadFile = function (filePath, type,successc, failc) {
  if (!filePath || filePath.length < 9) {
    uni.showModal({
      title: '文件错误',
      content: '请重试',
      showCancel: false,
    })
    return;
  }
	
	
	
	
	Vue.prototype.$u.api.uploadToken({file_type:type}).then(res => {
		if(res.code == 200){
			config.aliyunServerURL = `https://${res.result.token.Bucket}.${res.result.token.Region}.aliyuncs.com/`
			config.accessid = res.result.token.AccessKeyId
			config.AccessKeySecret = res.result.token.AccessKeySecret
			config.expiration = res.result.token.Expiration
			config.SecurityToken = res.result.token.SecurityToken
			config.policyBase64 = getPolicyBase64()
			config.signature = getSignature(config.policyBase64)
			
			//图片名字 可以自行定义，     这里是采用当前的时间戳 + 150内的随机数来给图片命名的
			const aliyunFileKey = res.result.token.Path + new Date().getTime() + Math.floor(Math.random() * 150) + (type == 'image' ? '.png' : '.mp3')
			
			uni.uploadFile({
			  url: config.aliyunServerURL,//开发者服务器 url
			  filePath: filePath,//要上传文件资源的路径
			  name: 'file',//必须填file
			  formData: {
			    'key': aliyunFileKey,
			    'policy': config.policyBase64,
			    'OSSAccessKeyId': config.accessid,
			    'signature': config.signature,
					'x-oss-security-token':config.SecurityToken,
			    'success_action_status': '200',
			  },
			  success: function (res) {
					console.log(res);
			    if (res.statusCode != 200) {
			      failc(new Error('上传错误:' + JSON.stringify(res)))
			      return;
			    }
			     successc(config.aliyunServerURL+aliyunFileKey);
			  },
			  fail: function (err) {
			    err.wxaddinfo = config.aliyunServerURL;
			    failc(err);
			  },
			})
		}else{
			uni.showToast({
				title:res.msg
			})
		}
	})
}

const getPolicyBase64 = function () {
  const policyText = {
    "expiration": config.expiration, //设置该Policy的失效时间，超过这个失效时间之后，就没有办法通过这个policy上传文件了 
    "conditions": [
      ["content-length-range", 0, 10 * 1024 * 1024] // 设置上传文件的大小限制,5mb
    ]
  };
  const policyBase64 = base64.encode(JSON.stringify(policyText));
  return policyBase64;
}

const getSignature = function (policyBase64) {
  const accesskey = config.AccessKeySecret;

  const bytes = Crypto.HMAC(Crypto.SHA1, policyBase64, accesskey, {
    asBytes: true
  });
  const signature = Crypto.util.bytesToBase64(bytes);
  return signature;
}

module.exports = uploadFile;